package com.tbit.main.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;

/**
 * @author LMY
 * @create 2020-10-23 9:09
 */
@Slf4j
public class AliSms {

    /**
     * 短信验证码发送
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @param productname
     * @param templateCode
     * @param phone
     * @param code
     */
    public static void sendSms(String accessKeyId, String accessKeySecret, String productname, String templateCode, String phone, String code) {
        log.info("阿里：短信验证码phone=" + phone + ",code=" + code);

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
        } catch (ClientException e) {
            log.error(e.getMessage(), e);
            log.error("连接阿里云短信服务异常", e);
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName(productname);
        request.setTemplateCode(templateCode);
        request.setTemplateParam("{\"code\":\"" + code + "\"}");

        SendSmsResponse sendSmsResponse = null;
        ;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            log.error("连接阿里云短信服务异常", e);
        }

        /**发送短信失败错误打印*/
        if (sendSmsResponse == null) {
            log.error("短信发送失败,phone=" + phone + "code=" + code);
            return;
        }
        if (!"OK".equals(sendSmsResponse.getMessage())) {
            log.error("阿里云短信错误信息=" + sendSmsResponse.getMessage());
        }
    }

    public static void main(String[] args) {
        sendSms("LTAI4FnKnw13axyQ1X8vfXRQ", "RjEeJA5SiFXA7CMIfkuKgLInPJGfTF", "小彬电单车", "SMS_171685113", "15079017029", "8527");
    }
}
